package org.hry.netty.bootstrap;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.channel.*;
import io.netty.channel.socket.nio.NioSocketChannel;
@ChannelHandler.Sharable
public class ServerHandler extends SimpleChannelInboundHandler<ByteBuf> {
    ChannelFuture connectFuture;

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, ByteBuf msg) throws Exception {
        if (connectFuture.isDone()) {
            System.out.println("connectFuture已经完成对应的工作");
        }
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        initClient(ctx.channel().eventLoop());

    }


    private void initClient(EventLoop eventLoop) {
        Bootstrap client = new Bootstrap();
        client.group(eventLoop).channel(NioSocketChannel.class).handler(new ClientInitializer());
        connectFuture = client.connect("localhost", 8899);
        connectFuture.addListener((ChannelFutureListener) future -> {
            if (future.isSuccess()) {
                System.out.println("客户端成功启动");
            } else {
                System.out.println("客户端启动失败");
                future.cause().printStackTrace();
            }
        });
    }


}


